{layout name="layout"}
<table class="layui-hide" id="demo" lay-filter="test"></table>

<script type="text/html" id="barDemo">
	<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
	<!-- <a class="layui-btn layui-btn-xs" lay-event="more">更多 <i class="layui-icon layui-icon-down"></i></a> -->
</script>

<script id="addForm" type="text/html">
	<div class="layer-form">
		<form class="layui-form layui-form-pane">
			<div class="layui-form-item">
				<label class="layui-form-label">职务名称</label>
				<div class="layui-input-block">
					<input type="text" name="group_name" autocomplete="off" placeholder="请输入" lay-verify="required"
						class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">权限</label>
				<div class="layui-input-block">
					<div id="add_routers"></div>
				</div>
			</div>
			
			<div class="layui-form-item">
				<button class="layui-btn" lay-submit lay-filter="addSubmit">确认</button>
				<button type="reset" class="layui-btn layui-btn-primary">重置</button>
			</div>
		</form>
	</div>
</script>

<script id="editForm" type="text/html">
	<div class="layer-form">
		<form class="layui-form layui-form-pane" lay-filter="editForm">
			<div class="layui-form-item">
				<label class="layui-form-label">职务名称</label>
				<div class="layui-input-block">
					<input type="text" name="group_name" autocomplete="off" placeholder="请输入" lay-verify="required"
						class="layui-input">
				</div>
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label">权限</label>
				<div class="layui-input-block">
					<div id="edit_routers"></div>
				</div>
			</div>
			<div class="layui-form-item">
				<button class="layui-btn" lay-submit lay-filter="editSubmit">确认</button>
				<button type="reset" class="layui-btn layui-btn-primary">重置</button>
			</div>
		</form>
	</div>
</script>


<script>
	function extractTree(bossArr, children) {
		//如果为空 返回空（防止 children 递归报错）
		if (!Array.isArray(bossArr) && !bossArr.length) return [];
		let list = [];
		const getObj = (arr) => {
			arr.forEach((row) => {
				let obj = {};
				obj = JSON.parse(JSON.stringify(row));
				list.push(obj);
				if (row[children]) {
					getObj(row[children]);
				}
			});
			return list;
		};
		return getObj(bossArr);
	}


	window.onload = () => {
		layui.use(function () { //亦可加载特定模块：layui.use(['layer', 'laydate', function(){
			//得到各种内置组件
			var layer = layui.layer //弹层
				,
				laypage = layui.laypage //分页
				,
				laydate = layui.laydate //日期
				,
				table = layui.table //表格
				,
				carousel = layui.carousel //轮播
				,
				upload = layui.upload //上传
				,
				element = layui.element //元素操作
				,
				slider = layui.slider //滑块
				,
				dropdown = layui.dropdown //下拉菜单
				, form = layui.form,
				tree = layui.tree;




			//执行一个 table 实例
			table.render({
				elem: '#demo',
				url: "{:url('/member/system/listgroup')}" //数据接口
				,
				page: true //开启分页
				,
				toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
				,
				totalRow: true //开启合计行
				,
				cols: [
					[ //表头
						{
							type: 'checkbox',
							fixed: 'left'
						}, {
							field: 'id',
							title: '#',
							width: 80,
							sort: true,
							fixed: 'left'
						}, {
							field: 'group_name',
							title: '职务名称'
						}, {
							fixed: 'right',
							width: 150,
							align: 'center',
							toolbar: '#barDemo'
						}
					]
				]
			});

			//监听头工具栏事件
			table.on('toolbar(test)', function (obj) {
				var checkStatus = table.checkStatus(obj.config.id),
					data = checkStatus.data; //获取选中的数据
				switch (obj.event) {
					case 'add':
						let layero = layer.open({
							type: 1,
							area: ['50%', '90%'], // 宽高
							content: $("#addForm").html(),
							success: () => {
								let routers = [];

								$.ajax({
									url: "{:url('/member/system/treeRouter')}",
									success: res => {
										let arr = res.data;
										tree.render({
											elem: '#add_routers',
											data: arr,
											showCheckbox: true,
											id: "addrouters"
										});
									}
								});



								form.on('submit(addSubmit)', function (data) {
									var field = data.field; // 获取表单字段值
									var checkedData = tree.getChecked('addrouters');
									let newList = extractTree(checkedData, 'children');
									let routerArr = [];
									let sdata = {};
									sdata.group_name = field.group_name;
									$.each(newList, (i, v) => {
										routerArr.push(v.id);
									});
									let routerStr = routerArr.join(",");
									sdata.routers = routerStr;

									$.ajax({
										url: "{:url('/member/system/addgroup')}",
										type: "POST",
										data: sdata,
										success: function (res) {
											if (res.code === 0) {
												layer.msg(res.msg, { icon: 1 });
												table.reload("demo");
											} else {
												layer.msg(res.msg, { icon: 2 });
											}
										}
									});

									return false; // 阻止默认 form 跳转
								});
							}
						});
						break;
					case 'update':
						if (data.length === 0) {
							layer.msg('请选择一行');
						} else if (data.length > 1) {
							layer.msg('只能同时编辑一个');
						} else {
							let layero = layer.open({
								type: 1,
								area: ['50%', '90%'], // 宽高
								content: $("#editForm").html(),
								success: () => {
									let temp = checkStatus.data[0];

									$.ajax({
										url: "{:url('/member/system/treeRouter')}",
										success: res => {
											let arr = res.data;
											tree.render({
												elem: '#edit_routers',
												data: arr,
												showCheckbox: true,
												id: "editrouters"
											});
											if (temp.routers != null) {
												let tempRouter = temp.routers.split(",");

												$.ajax({
													type: "post",
													url: "{:url('/member/system/getRouters')}",
													data: { "ids": tempRouter },
													success: res => {
														let tempArr1 = res.data;
														let tempArr2 = [];
														$.each(tempArr1, (i, v) => {
															tempArr2.push(parseInt(v));
														});
														tree.setChecked('editrouters', tempArr2);
													}
												});
											}
										}
									});

									form.val('editForm', {
										"group_name": temp.group_name
									});



									form.on('submit(editSubmit)', function (data) {
										var field = data.field; // 获取表单字段值

										var checkedData = tree.getChecked('editrouters');
										let newList = extractTree(checkedData, 'children');
										let routerArr = [];
										let sdata = {};
										sdata.group_name = field.group_name;
										$.each(newList, (i, v) => {
											routerArr.push(v.id);
										});
										let routerStr = routerArr.join(",");
										sdata.routers = routerStr;
										sdata.id = temp.id;

										$.ajax({
											url: "{:url('/member/system/editgroup')}",
											type: "POST",
											data: sdata,
											success: function (res) {
												if (res.code === 0) {
													layer.msg(res.msg, { icon: 1 });
													table.reload("demo");
												} else {
													layer.msg(res.msg, { icon: 2 });
												}
											}
										})

										return false; // 阻止默认 form 跳转
									});
								}
							});
						}
						break;
					case 'delete':
						if (data.length === 0) {
							layer.msg('请选择一行');
						} else {
							let ids = [];
							$.each(data, (i, v) => {
								ids.push(v.id);
							});
							$.ajax({
								url: "{:url('/member/system/softdeleteGroup')}",
								data: { ids },
								type: "post",
								success: res => {
									if (res.code === 0) {
										layer.msg(res.msg, { icon: 1 });
										setTimeout(() => {
											window.location.reload();
										}, 1500);
									} else {
										layer.msg(res.msg, { icon: 2 });
									}
								}
							});

						}
						break;
				};
			});

			//监听行工具事件
			table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
				var data = obj.data //获得当前行数据
					,
					layEvent = obj.event; //获得 lay-event 对应的值
				if (layEvent === 'edit') {
					let layero = layer.open({
						type: 1,
						area: ['50%', '90%'], // 宽高
						content: $("#editForm").html(),
						success: () => {
							let temp = data;

							$.ajax({
								url: "{:url('/member/system/treeRouter')}",
								success: res => {
									let arr = res.data;
									tree.render({
										elem: '#edit_routers',
										data: arr,
										showCheckbox: true,
										id: "editrouters"
									});
									if (temp.routers != null) {
										let tempRouter = temp.routers.split(",");

										$.ajax({
											type: "post",
											url: "{:url('/member/system/getRouters')}",
											data: { "ids": tempRouter },
											success: res => {
												let tempArr1 = res.data;
												let tempArr2 = [];
												$.each(tempArr1, (i, v) => {
													tempArr2.push(parseInt(v));
												});
												tree.setChecked('editrouters', tempArr2);
											}
										});
									}
								}
							});

							form.val('editForm', {
								"group_name": temp.group_name
							});



							form.on('submit(editSubmit)', function (data) {
								var field = data.field; // 获取表单字段值

								var checkedData = tree.getChecked('editrouters');
								let newList = extractTree(checkedData, 'children');
								let routerArr = [];
								let sdata = {};
								sdata.group_name = field.group_name;
								$.each(newList, (i, v) => {
									routerArr.push(v.id);
								});
								let routerStr = routerArr.join(",");
								sdata.routers = routerStr;
								sdata.id = temp.id;

								$.ajax({
									url: "{:url('/member/system/editgroup')}",
									type: "POST",
									data: sdata,
									success: function (res) {
										if (res.code === 0) {
											layer.msg(res.msg, { icon: 1 });
											table.reload("demo");
										} else {
											layer.msg(res.msg, { icon: 2 });
										}
									}
								})

								return false; // 阻止默认 form 跳转
							});
						}
					});

				} else if (layEvent === 'delete') {
					let id = data.id;
					let ids = [];
					ids.push(id);
					$.ajax({
						url: "{:url('/member/system/softdeleteGroup')}",
						data: { ids },
						type: "post",
						success: res => {
							if (res.code === 0) {
								layer.msg(res.msg, { icon: 1 });
								setTimeout(() => {
									window.location.reload();
								}, 1500);
							} else {
								layer.msg(res.msg, { icon: 2 });
							}
						}
					});
				}
				else if (layEvent === 'more') {
					//下拉菜单
					dropdown.render({
						elem: this //触发事件的 DOM 对象
						,
						show: true //外部事件触发即显示
						,
						data: [{
							title: '编辑',
							id: 'edit'
						}, {
							title: '删除',
							id: 'del'
						}],
						click: function (menudata) {
							if (menudata.id === 'del') {
								layer.confirm('真的删除行么', function (index) {
									obj.del(); //删除对应行（tr）的DOM结构
									layer.close(index);
									//向服务端发送删除指令
								});
							} else if (menudata.id === 'edit') {
								layer.msg('编辑操作，当前行 ID:' + data.id);
							}
						},
						align: 'right' //右对齐弹出（v2.6.8 新增）
						,
						style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
					})
				}
			});




		});

	};
</script>